package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/")//所有的请求都要进这个InitServlet
public class InitServlet extends HttpServlet {

    protected Map<String,BaseServlet> maps=new HashMap<>();

    @Override
    public void init() throws ServletException {
        maps.put("/user",new UserServlet());
        maps.put("/goods",new GoodsServlet());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String opr = req.getParameter("opr");
        System.out.println(">>>>>>>>>>>InitServlet  " + opr);
        // resp.getWriter().print(">>>>>>>>>>InitServlet:"+opr+"<<<<<<<<<<");
        String url = req.getRequestURI();
        url = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));

        BaseServlet baseServlet = maps.get(url);
        try{
            baseServlet.execute(req, resp);
        }catch (InvocationTargetException e){
            throw new  RuntimeException(e);
        }catch (IllegalAccessException e){

            throw new  RuntimeException(e);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
